<?php
namespace app\admin\controller\soft;
use app\providers\BaseController;
use think\Image;
use OSS\OssClient;
use OSS\Core\OssException;
use think\facade\Db;
use hg\apidoc\annotation as Apidoc;

/**
 * @Apidoc\Title("上传管理")
 * @Apidoc\Group("base")
 * @Apidoc\Sort(2)
 */
class Upload extends BaseController 
{
	
	protected $tableName = 'xw_system_upload';  			//表名
   
    /**
    * 上传文件
    *  @Apidoc\Author("weifashi")
    * @Apidoc\Url("admin/soft/upload/upload")
    * @Apidoc\Method("POST")
    * @Apidoc\Param("fkGuid", require=true,default="",desc="文件guid" )
    * @Apidoc\Param("ywName", require=true, default="",desc="业务名称" )
    * @Apidoc\Param("fkType", require=true, default="",desc="业务类型" )
    * @Apidoc\Param("desc", require=true, default="",desc="描述" )
    * @Apidoc\Param("classify_id", require=true, default="",desc="所属系统分类id" )
    */
	public function upload($fkGuid='',$ywName='',$fkType='',$desc='',$classify_id=0){
		if( empty($fkGuid) ) throw new \think\Exception('fkGuid不能为空');
		if( empty($ywName) ) throw new \think\Exception('ywName不能为空');
		if( empty($fkType) ) throw new \think\Exception('fkType不能为空');
						
		$files = request()->file();
		
        $config = env('SYSTEM_BASE_CONFIG_FILE');
        
		$fileId = 0;
	    foreach($files as $file){
			//保存的数据
			$data = [];
			
			//文件信息
			$fileType = $file->getType();
			$fileName = $file->getOriginalName();
			$tmpName = $file->getPathName();
			$fileSize = $file->getSize();
			$fileExt = substr($fileName,strrpos($fileName,'.')+1); 
			
			if($config["type"] == 'oss'){
		        try {
		        	@error_reporting (E_ALL & ~E_NOTICE & ~E_WARNING);
			     	$keyId = $config['accessKeyId'];
			        $keySecret = $config['accessKeySecret'];
			        $endpoint = $config['endpoint']; 
			        $catalog= $config['catalog'];
			        $auth = new OssClient($keyId,$keySecret,$endpoint);
			        $dst = $catalog.date('ymd').'/'.md5(time()).''.'-'.$fileName;  
		            $result = $auth->uploadFile($config['bucket'],$dst,$tmpName);
					$info = $result['info'];
					$filePath =  $info['url'];
					$data['duration'] = $info['total_time']; //这个获得的便是音频文件的时长
		        } catch (OssException $e) {
		        	return \Api::ReError($e->getMessage());
		        }
			}else{
				$filePath = \think\facade\Filesystem::putFile( 'uploads', $file);
				//如果是图片就压缩
				if(strstr($filePath,".jpg") || strstr($filePath,".png") || strstr($filePath,".gif")){
					$filePath2 = root_path().'/runtime/storage/'.$filePath;
					$image = Image::open($filePath2);
					$image->thumb(3000, 3000)->save($filePath2); 
					$data['width'] = $image->width();
					$data['height'] = $image->height();
				}
				//如果是音频就获取时长
				if(strstr($filePath,".mp3") || strstr($filePath,".mp4")){
					include_once(root_path().'/extend/lib/getid3/getid3.php');
					$getID3 = new \getID3();
					$thisFileInfo = $getID3->analyze($filePath); //分析文件，$path为音频文件的地址
					$data['duration'] = round($thisFileInfo['playtime_seconds'],2) ; //音频文件的时长
				}
			}
			
			$data['file_name']= $fileName;
	    	$data['file_path']=  $filePath;
	    	$data['file_guid']= "$fkGuid";
	    	$data['file_type']= "$fkType";
	    	$data['file_buss_type']= "$ywName";
	    	$data['file_description']="$desc";
	    	$data['type']= $fileType;
	    	$data['size']= $fileSize;
	    	$data['ext']= $fileExt;
	    	$data['classify_id']= $classify_id;
	    	$fileId = Db::table(  $this->tableName )->insertGetId($data);
	    }

		if($fileId){
			if( strstr($data['file_path'],"http://") ||  strstr($data['file_path'],"https://") ){
				$file_path = $data['file_path'];
			}else{
				$file_path = env('APP_HOST').'/'.str_replace("\\","/",$data['file_path']);
				$file_path = '/admin/soft/upload/downloadHandler?file_id='.$fileId;
			}
			
			return \Api::ReSucess(["id"=> $fileId,"src"=>$file_path],'上传成功！');
		}else{
			return \Api::ReError('上传失败！');
		}
		
	}

	
    /**
    * 获取附件
    *  @Apidoc\Author("weifashi")
    * @Apidoc\Url("admin/soft/upload/getFileList")
    * @Apidoc\Method("POST")
    * @Apidoc\Param("fkGuid", require=true,default="",desc="文件guid" )
    * @Apidoc\Param("ywName", require=true, default="",desc="业务名称" )
    * @Apidoc\Param("fkType", require=true, default="",desc="业务类型" )
    */
	public function getFileList($fkGuid,$ywName,$fkType){
		$data = Db::table($this->tableName)
			->where("file_guid='$fkGuid' and file_buss_type = '$ywName' and file_type= '$fkType' ")
			->field("*")
			->order('is_default desc,create_time')
			->select();
    	return \Api::ReSucess($data,'');
	}
	
    /**
    *  获取附件列表
    *  @Apidoc\Author("weifashi")
    * @Apidoc\Url("admin/soft/upload/getClassifyFileList")
    * @Apidoc\Method("POST")
    * @Apidoc\Param("classify_ids", require=true,default="",desc="系统分类ids" )
    * @Apidoc\Param("name", require=true, default="",desc="文件名称" )
    * @Apidoc\Param("page", require=true, default="1",desc="第几页" )
    * @Apidoc\Param("limit", require=true, default="30",desc="每页多少条" )
    */
	public function getClassifyFileList($classify_ids,$name='',$page=1,$limit=30){
		$model = Db::table( $this->tableName )
			->where("classify_id",'in',$classify_ids)
			->where("file_name",'like',"%$name%")
			->order('is_default desc,create_time desc');
		
		$fileList = $model->page($page,$limit)->select();
		foreach($fileList as $key => $val){
			$val['file_path'] = '/admin/soft/upload/downloadHandler?file_id='.$val['file_id'];
			$fileList[$key] = $val;
		}	
			
		$data = [
			'count'=>$model->count(),
			'list'=> $fileList
		];	
		
    	return \Api::ReSucess($data,'');
	}
	
	
    /**
    *  删除附件
    *  @Apidoc\Author("weifashi")
    * @Apidoc\Url("admin/soft/upload/deleteFile")
    * @Apidoc\Method("POST")
    * @Apidoc\Param("fileIds", require=true,default="",desc="附件ids" )
    */
	public function deleteFile($fileIds){
		$referer = request()->server('HTTP_REFERER');
        $urlQuery = html_entity_decode(parse_url($referer)['query']);
        $urlQuery = explode("&",$urlQuery); $urlQuery = explode("=",$urlQuery[2]);
        $db = Db::table($this->tableName)->where('file_guid',$urlQuery[1] )->where("file_id","in",$fileIds);
        $result = $db->select();
		if(!$result){
			return \Api::ReError("file_id不存在");
		}else{
			foreach ($result as $fies){
				//$savepath = str_replace(public_path(),'.',$fies['file_path']);
				@unlink( root_path().'/runtime/storage/'.$fies['file_path']);//删除文件
			}
			Db::table($this->tableName)->where("file_id","in",$fileIds)->delete();
		}
		return \Api::ReSucess($result,'');
	}
	
  	/**
    *  设置默认
    *  @Apidoc\Author("weifashi")
    * @Apidoc\Url("admin/soft/upload/setDefault")
    * @Apidoc\Method("POST")
    * @Apidoc\Param("file_id", require=true,default="",desc="附件id" )
    * @Apidoc\Param("type", require=true,default="",desc="1=默认, 0 等于取消默认		" )
    */
	public function setDefault($file_id,$type){
		if(!$file_id || (!$type && $type !=='0') ){
			return \Api::ReError("参数错误");
		}
		$file_guids = Db::table($this->tableName)->where("file_id","=",$file_id)->column('file_guid');
		if(!$file_guids[0]){
			return \Api::ReError("文件不存在");
		}
		Db::table($this->tableName)->where("file_guid",$file_guids[0])->update(["is_default"=>0]);
		$result =  Db::table($this->tableName)->where("file_id",$file_id)->update(["is_default"=>$type]);
		if($result === false){
			return \Api::ReError("操作失败");
		}
		return \Api::ReSucess();
	}
	
    /**
    *  下载文件
    *  @Apidoc\Author("weifashi")
    * @Apidoc\Url("admin/soft/upload/downloadHandler")
    * @Apidoc\Method("All")
    * @Apidoc\Param("file_id", require=true,default="",desc="附件id" )
    * @Apidoc\Param("is_ziz", require=true,default="0",desc="是否打包下载： 1打包, 0不打包" )
    */
	public function downloadHandler($file_id,$is_ziz=false){
        $referer = request()->server('HTTP_REFERER');
        $urlQuery = html_entity_decode(parse_url($referer)['query']);
        $urlQuery = explode("&",$urlQuery); $urlQuery = explode("=",$urlQuery[2]);
        $db = Db::table($this->tableName)->where('file_guid',$urlQuery[1] )->where("file_id","in",$file_id);
        $data = $db->select();
        if(!$data[0]){
            return \Api::ReError("文件不存在！");
        }else{
            $files=[];
            foreach ($data as $fies){
                $fileExt= $fies['ext'];
                $savepath = str_replace(env('APP_HOST'),'.',$fies['file_path']);
                $savepath = root_path().'/runtime/storage/'.$savepath;
                $fileName = str_replace('.'.$fileExt,'',$fies['file_name']);
                $filePath = $savepath = realpath($savepath); $fp = fopen($savepath, 'rb');
                if (!$filePath || !$fp) {
                    header('HTTP/1.1 404 Not Found');
                    echo "
                        Error: 404 Not Found.(server file path error)
                        </br>
                        </br>
                        【 $fileName 】文件不存在，或已被删除
                    ";
                    exit;
                }
                if(!$is_ziz){
                    if(  
                        strstr($savepath, '.png')  || 
                        strstr($savepath, '.jpeg')  || 
                        strstr($savepath, '.bmp') || 
                        strstr($savepath, '.gif') 
                    ){
                        if($size = request()->get('size')){
                            $minFilePath = str_replace(".","_{$size}.",$filePath);
                            $savePath = root_path().'/runtime/storage/'.$minFilePath;
                            if( !file_exists($savePath) ){
                                $image = Image::open($filePath);
                                $image->thumb($size, $size)->save($savePath); 
                            }
                            $filePath = $minFilePath;
                        }
                        $this-> imagedestroys( public_path().'/'. $filePath );
                    }else{
                        $this->download($savepath,$fileName);
                    }
                }else{
                    $files[] = $filePath;
                }
            }
            if($is_ziz){
                require root_path().'/extend/base/files/Zip.php';
                $zipname = "download.zip";
                (new \PHPzip) -> zip($files,$zipname);
                header('Content-Type: application/zip');
                header('Content-disposition: attachment; filename='.$zipname);
                header('Content-Length: ' . filesize($zipname));
                readfile($zipname);
                @unlink($zipname);
            }
        }
    }
	
	/**
    * 下载方法
    * @access private
    * @param string $file 		
    * @param string $name 		
    * @return  array
    */
	private function download($file, $name = '') {
		$fileName = $name ? $name : pathinfo($file, PATHINFO_FILENAME);
		$filePath = realpath($file);
		$fp = fopen($filePath, 'rb');
		if (!$filePath || !$fp) {
			header('HTTP/1.1 404 Not Found');
			echo "
				Error: 404 Not Found.(server file path error)</br>
				文件不存在，或已被删除
			";
			exit ;
		}
		$fileName = $fileName . '.' . pathinfo($filePath, PATHINFO_EXTENSION);
		$encoded_filename = urlencode($fileName);
		$encoded_filename = str_replace("+", "%20", $encoded_filename);
		header('HTTP/1.1 200 OK');
		header("Pragma: public");
		header("Expires: 0");
		header("Content-type: application/octet-stream");
		header("Content-Length: " . filesize($filePath));
		header("Accept-Ranges: bytes");
		header("Accept-Length: " . filesize($filePath));
		$ua = $_SERVER["HTTP_USER_AGENT"];
		if (preg_match("/MSIE/", $ua)) {
			header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
		} else if (preg_match("/Firefox/", $ua)) {
			header('Content-Disposition: attachment; filename*="utf8\'\'' . $fileName . '"');
		} else {
			header('Content-Disposition: attachment; filename="' . $fileName . '"');
		}
		fpassthru($fp);
		exit ;
	}
   	
   	/**
    *  获取描述
    *  @Apidoc\Author("weifashi")
    * @Apidoc\Url("admin/soft/upload/getDesc")
    * @Apidoc\Method("POST")
    * @Apidoc\Param("file_path", require=true,default="",desc="file_path" )
    */
	public function getDesc($file_path){
		if(!$file_path){
			return \Api::ReError("参数错误");
		}
		$file_path = str_replace(env('APP_HOST').'/',"",$file_path);
		$file_path = str_replace('/',"\\",$file_path);
		$desc = Db::table($this->tableName)->where("file_path",$file_path)->value('file_description');
		return \Api::ReSucess($desc ?: '');
	}
	
   	/**
    *  更新描述
    *  @Apidoc\Author("weifashi")
    * @Apidoc\Url("admin/soft/upload/updateDesc")
    * @Apidoc\Method("POST")
    * @Apidoc\Param("file_path", require=true,default="",desc="file_path" )
    * @Apidoc\Param("desc", require=true,default="",desc="描述" )
    */
	public function updateDesc($file_path,$desc){
		if(!$file_path || !$desc){
			return \Api::ReError("参数错误");
		}
		$file_path = str_replace(env('APP_HOST').'/',"",$file_path);
		$file_path = str_replace('/',"\\",$file_path);
		Db::table($this->tableName)->where("file_path",$file_path)->update([
			'file_description'=>$desc
		]);
		return \Api::ReSucess();
	}
	
   	/**
    *  更新名称
    *  @Apidoc\Author("weifashi")
    * @Apidoc\Url("admin/soft/upload/updateName")
    * @Apidoc\Method("POST")
    * @Apidoc\Param("file_id", require=true,default="",desc="附件id" )
    * @Apidoc\Param("name", require=true,default="",desc="新名称" )
    */
	public function updateName($file_id,$name){
		Db::table($this->tableName)->where("file_id",$file_id)->update(['file_name'=>$name]);
		return \Api::ReSucess();
	}
	
	
	/**
    * 输出图片
    */
	private function imagedestroys($img) {
		$info = getimagesize($img);
	    $imgExt = image_type_to_extension($info[2], false);  //获取文件后缀
	    $fun = "imagecreatefrom{$imgExt}";
	    $imgInfo = $fun($img);   
		$mime = "";      
		if( strstr($img, '.png') !=-1)  $mime = 'png';
		if( strstr($img, '.jpeg') !=-1)  $mime = 'jpeg';
		if( strstr($img, '.bmp') !=-1)  $mime = 'bmp';
		if( strstr($img, '.gif') !=-1)  $mime = 'gif';
	    header('Content-Type: image/'.$mime);
	    $quality = 100;  if($imgExt == 'png') $quality = 9;  //输出质量,JPEG格式(0-100),PNG格式(0-9)
	    $getImgInfo = "image{$imgExt}";
        $getImgInfo($imgInfo, null, $quality);    //2.将图像输出到浏览器或文件
        imagedestroy($imgInfo);
	}
	
}